import axios from "axios";
import qs from "qs";

// 检测是否为纯粹的对象
const isPlainObject = function isPlainObject(obj) {
  let proto, Ctor;
  if (!obj || Object.prototype.toString.call(obj) !== "[object Object]")
    return false;
  proto = Object.getPrototypeOf(obj);
  if (!proto) return true;
  Ctor = proto.hasOwnProperty("constructor") && proto.constructor;
  return typeof Ctor === "function" && Ctor === Object;
};

axios.defaults.baseURL = "";
axios.defaults.timeout = 60000;
axios.defaults.transformRequest = (data) => {
  if (isPlainObject(data)) return qs.stringify(data);
  return data;
};
axios.interceptors.request.use((config) => {
  // 针对于部分接口，我们携带令牌和签名信息
  let apiList = [
      "/check_login",
      "/user_info",
      "/user_update",
      "/store",
      "/store_remove",
      "/store_list",
    ],
    token = localStorage.getItem("token");
  if (apiList.includes(config.url.replace("/api", "")) && token) {
    let time = +new Date();
    config.headers["authorzation"] = token;
    config.headers["time"] = time;
  }
  return config;
});
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (reason) => {
    console.log(reason);
    return Promise.reject(reason);
  }
);
export default axios;
